/*
 * @Description:
 * @Author: wangqi
 * @Date: 2024-08-30 18:21:50
 * @LastEditTime: 2024-09-09 11:16:02
 * @LastEditAuthor: wangqi
 */
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from 'src/entities/User';
// import { Logger } from 'nestjs-pino';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly userRepository: Repository<User>,
    // private readonly logger: Logger,
  ) {}

  async create(user: User) {
    const userRow = await this.userRepository.create(user);
    return this.userRepository.save(userRow);
  }

  findAll() {
    try {
      throw new Error('故意错误');
      // throw new HttpException('禁止访问!', HttpStatus.FORBIDDEN);
      return this.userRepository.find();
    } catch (error) {
      // throw new HttpException('禁止访问-catch!', HttpStatus.FORBIDDEN);

      const obj = {
        status: HttpStatus.FORBIDDEN,
        message: '禁止访问!',
        data: null,
      };
      throw new HttpException(obj, HttpStatus.FORBIDDEN);
    }
    // return this.userRepository.query(`select * from user;`);
  }
  find(username: string) {
    /* 这里接口报错走 全局 httpException */
    // return this.userRepository.findOne({ where: { username } });
    const sql = `select * from user where username='${username}'`;
    // this.logger.warn('youyouyo select *--- select * 我我哦我');
    return this.userRepository.query(sql);

    // ---------------------------------
    /* 路由手动覆盖全局 httpException */
    // try {
    //   throw new Error('故意错误');
    //   // return this.userRepository.findOne({ where: { username } });
    //   const sql = `select * from user where username='${username}'`;
    //   return this.userRepository.query(sql);
    // } catch (error) {
    //   throw new HttpException('禁止访问-catch!!', HttpStatus.FORBIDDEN);
    // }
  }

  async update(id: number, user) {
    const userTable = await this.userRepository.find();
    userTable.forEach((item) => {
      if (item.id === user.id) {
        // this.userRepository.update(user.id, user);
        const sql = `update from user set username=${user.username}, password=${user.password} where id=${id}`;
        this.userRepository.query(sql);
      }
    });

    const result = {
      status: 200,
      code: 0,
    };
    return result;
  }

  remove(id: number) {
    // return this.userRepository.delete(id);
    const sql = `delete from user where id='${id}'`;
    return this.userRepository.query(sql);
  }

  findProfile(id: number) {
    return this.userRepository.findOne({
      where: { id },
      relations: ['profile'],
    });

    // cosnt sql = `SELECT * FROM `user` LEFT JOIN `profile` ON USER.id = PROFILE.user_id`
    // return this.userRepository.query(sql)
  }
}
